package com.aischool.service;

import java.util.Date;
import java.util.List;

import com.aischool.common.model.WxUser;
import com.aischool.utils.DateUtil;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;

public class WeixinUserService {
	static Log log = Log.getLog(WeixinUserService.class);
	
	@Inject
	SysUserService sysUserService;
	
	
	public boolean save(String openId, String nickName, String unionid, String headimgurl, 
						String country,String city,String province ,int sex,
						String access_token, Date expires_date, String token_scope, 
						int user_id){
		
		log.error("openId:"+openId+" nickName:"+nickName+" unionid:"+unionid+ " headimgurl:"+headimgurl+" country:"+country+" city:"+city+" province:"+province+" sex:"+sex);
		
		/**
		 * 1、判断openId 是否存在 
		 *    如果存在就update
		 *    如果不存在就保存
		 */
		WxUser wxuser = WxUser.dao.findById(openId);
		boolean is_haved = false;
		if (wxuser != null) {
			is_haved = true;
		}else {
			wxuser = new WxUser();
		}

		wxuser.setOpenid(openId);
		wxuser.setNickname(nickName);
		wxuser.setUnionid(unionid);
		wxuser.setHeadimgurl(headimgurl);
		wxuser.setCountry(country);
		wxuser.setCity(city);
		wxuser.setProvince(province);
		wxuser.setSex(sex);
		wxuser.setUpdateTime(new Date());
		wxuser.setAccessToken(access_token);
		wxuser.setExpiresTime(expires_date);
		wxuser.setTokenScope(token_scope);
		wxuser.removeNullValueAttrs();
		
		boolean bf = false;
		if (is_haved) {
			bf =  wxuser.update();
		}else {
			wxuser.setAddTime(new Date());
			bf =  wxuser.save();
		}
		
		if (bf) {
			bf = sysUserService.updateWxOpenId(user_id, openId, headimgurl);
		}
		
		return bf;
	}
	
	public void sendLeaveNotes(int class_id, Date cur_date) {
		String str_sql = "SELECT a.*, b.wx_errcode, c.class_name, d.student_name, e.org_name, f.parent_name, u.wx_openid  \r\n" + 
				"FROM ai_roll_call a \r\n" + 
				"LEFT JOIN wx_leave_notes b ON b.roll_call_id = a.roll_call_id \r\n" + 
				"INNER JOIN ai_class c ON c.class_id = a.class_id \r\n" + 
				"INNER JOIN ai_student d ON d.student_id = a.student_id\r\n" + 
				"INNER JOIN ai_org e ON e.org_id = c.org_id \r\n" + 
				"INNER JOIN ai_parent f ON f.student_id = a.student_id \r\n" + 
				"INNER JOIN sys_user u ON u.user_id = f.user_id \r\n" + 
				"WHERE b.wx_errcode IS NULL AND a.roll_call_state = 5 AND a.class_id = ? AND a.add_time = ?";
		List<Record> listrds = Db.find(str_sql, class_id, cur_date);
		if (listrds != null && listrds.size() > 0) {
			// 启动多线程
			new Thread(()->{
		        for(int i=0; i<listrds.size(); i++) {
		        	sendLeaveNote(listrds.get(i));
		        }
		    }).start();

		}
	}
	
	public void sendLeaveNote(Record rd) {
		if (StrKit.isBlank(rd.getStr("wx_openid"))) {
			return;
		}
		
		try {
			
			int rcid = rd.getInt("roll_call_id");
			Date nowdate = new Date();
			
			// 模板消息，发送测试：pass
			ApiResult result = TemplateMsgApi.send(TemplateData.New()
				// 消息接收者
				.setTouser(rd.getStr("wx_openid"))
				// 模板id
				.setTemplate_id("SXBp14cAN0_lf5KpyRXdgTLVHmrS1YnYDUC_O5jaE3Q")
				
				// 模板参数
				.add("parent_name", rd.getStr("parent_name"), "#999")
				.add("student_name", rd.getStr("student_name"), "#999")
				.add("leave_time", DateUtil.getDate(nowdate, "yyyy-MM-dd HH:mm:ss"), "#999")
				.add("class_name", rd.getStr("class_name"), "#999")
				.add("org_name", rd.getStr("org_name"), "#999")
				.build());
			
			int errcode = result.getInt("errcode");
			String errmsg = result.getStr("errmsg");
			String msgid = result.getLong("msgid").toString();
			
			
			Db.update("INSERT INTO wx_leave_notes(roll_call_id, wx_msgid, wx_errcode, wx_errmsg, add_time)\r\n" + 
					"VALUES(?,?,?,?,?)\r\n" + 
					"ON CONFLICT(roll_call_id) \r\n" + 
					"DO UPDATE SET wx_msgid = ?, wx_errcode = ?, wx_errmsg = ?, add_time = ?",
					rcid, msgid, errcode, errmsg, nowdate, msgid, errcode, errmsg, nowdate);
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		

	}
}
